<?php /* УТФ-8:fix */

class SPImodel__profiles extends SPImodel__dummy
{
    public function is_permit( $permissions, $checking_perm_id )
    {
        $permissions = (int) $permissions;
        $checking_perm_id = (int) $checking_perm_id;

        if( $checking_perm_id == SPI_IAM_PERM_GUEST )
        {
            return $permissions === 0;
        }

        return ( $permissions & $checking_perm_id ) == $checking_perm_id;
    }

    public function qfield_permission( $fieldname, $permission_id )
    {
        if( is_array( $permission_id ) === false )
        {
            $permission_id = (int) $permission_id;

            if( $permission_id == 0)
            {
                return '';
            }

            $permission_id = array( $permission_id );
        }
        elseif( count( $permission_id ) == 0 )
        {
            return '';
        }

        $qres = '';

        foreach( $permission_id as $one_id )
        {
            $one_id = (int) $one_id;
            $qres .= ( $qres ? ' OR ' : '' )
                   . " ( {$fieldname} & {$one_id} ) = {$one_id} "
                   ;
        }


        return " AND ( {$qres} ) ";
    }

    public function build_permissions_keys( $permissions )
    {
        $permissions = (int) $permissions;

        $r = array();

        if( $permissions === 0 )
        {
            $r[SPI_IAM_PERM_GUEST] = true;
        }
        else
        {
            $r[SPI_IAM_PERM_ADMIN]              = $this->is_permit( $permissions, SPI_IAM_PERM_ADMIN );
            $r[SPI_IAM_PERM_USER]               = $this->is_permit( $permissions, SPI_IAM_PERM_USER );
        }

        return $r;
    }

    public function get_by_login_n_password( $login, $passwd )
    {
        $store = SPIstore::I();

        $query = 'SELECT * FROM '.SPIcfg::$store['table:profiles'].' WHERE email = \''.$store->quote( $login ).'\' AND passwd = \''.$store->quote( $passwd ).'\' LIMIT 1';

        $qresult = $store->query( $query );

        if( $qresult === false )
        {
            return false;
        }
		
        return $qresult->fetch_and_close();
    }

    public function get_by_id( $profile_id )
    {
        $query =    " SELECT * "
               .      " FROM ".SPIcfg::$store['table:profiles']
               .     " WHERE id=" . (int) $profile_id
               ;

        return SPIstore::I()->query( $query )->fetch_and_close();
    }
}
